//
//  AISMusicPlayer.m
//  CantonController
//
//  Created by Ares on 5/6/15.
//  Copyright (c) 2015 Ares. All rights reserved.
//

#import "AISMusicPlayer.h"

@interface AISMusicPlayer() {
    MPMusicPlayerController *musicPlayer;
}
@end

AISMusicPlayer *gSharedInstance = nil;

@implementation AISMusicPlayer

+ (AISMusicPlayer *)sharedInstance {
    if (nil == gSharedInstance) {
        gSharedInstance = [[AISMusicPlayer alloc] init];
    }
    
    return gSharedInstance;
}

- (id)init {
    self = [super init];
    if (nil != self) {
        musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
        // By default, an application music player takes on the shuffle and repeat modes
        //		of the built-in iPod app. Here they are both turned off.
        [musicPlayer setShuffleMode:MPMusicShuffleModeOff];
        [musicPlayer setRepeatMode:MPMusicRepeatModeAll];
        
        [self registerForMediaPlayerNotifications];
    }
    
    return self;
}

// To learn about notifications, see "Notifications" in Cocoa Fundamentals Guide.
- (void)registerForMediaPlayerNotifications {
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    
    [notificationCenter addObserver: self
                           selector: @selector(handle_NowPlayingItemChanged:)
                               name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
                             object: musicPlayer];
    [notificationCenter addObserver: self
                           selector: @selector(handle_PlaybackStateChanged:)
                               name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
                             object: musicPlayer];
    /*
     // This sample doesn't use libray change notifications; this code is here to show how
     //		it's done if you need it.
     [notificationCenter addObserver: self
     selector: @selector (handle_iPodLibraryChanged:)
     name: MPMediaLibraryDidChangeNotification
     object: musicPlayer];
     
     [[MPMediaLibrary defaultMediaLibrary] beginGeneratingLibraryChangeNotifications];
     */
    
    [musicPlayer beginGeneratingPlaybackNotifications];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver: self
                                                    name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
                                                  object: musicPlayer];
    [[NSNotificationCenter defaultCenter] removeObserver: self
                                                    name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
                                                  object: musicPlayer];
    
    [musicPlayer endGeneratingPlaybackNotifications];
}

#pragma mark Music notification handlers

- (void) handle_NowPlayingItemChanged:(id)notification {
    if ([self.delegate respondsToSelector:@selector(musicPlayerDidPlayingItemChanged)]) {
        [self.delegate musicPlayerDidPlayingItemChanged];
    }
}

- (void)handle_PlaybackStateChanged:(id)notification {
    if ([self.delegate respondsToSelector:@selector(musicPlayerDidPlaybackStateChanged)]) {
        [self.delegate musicPlayerDidPlaybackStateChanged];
    }
}

- (void) handle_iPodLibraryChanged: (id) notification {
    
    // Implement this method to update cached collections of media items when the 
    // user performs a sync while your application is running. This sample performs 
    // no explicit media queries, so there is nothing to update.
}

#pragma mark functions

- (void)setPlayerItemCollection:(MPMediaItemCollection *)playerItemCollection {
    _playerItemCollection = playerItemCollection;
    [musicPlayer setQueueWithItemCollection:playerItemCollection];
}

- (BOOL)hasMusicToPlay {
    return nil != musicPlayer.nowPlayingItem;
}

- (BOOL)isNowPlayingItem:(MPMediaItem *)item {
    return item == musicPlayer.nowPlayingItem;
}

- (void)playMusicWithIndex:(NSInteger)index {
    NSArray *items = [self.playerItemCollection items];
    MPMediaItem *item = [items objectAtIndex:index];
    [musicPlayer setNowPlayingItem:item];
    [musicPlayer play];
}

- (void)play {
    [musicPlayer play];
}

- (void)pause {
    [musicPlayer pause];
}

- (void)next {
    [musicPlayer skipToNextItem];
}

- (void)previous {
    [musicPlayer skipToPreviousItem];
}

- (NSString *)currentTrackName {
    if (nil == musicPlayer.nowPlayingItem) {
        return @"Select Tracks to Play";
    }
    return musicPlayer.nowPlayingItem.title;
}

- (NSString *)currentTrackArtist {
    if (nil == musicPlayer.nowPlayingItem) {
        return @"Unknown";
    }
    return musicPlayer.nowPlayingItem.artist;
}

- (UIImage *)currentTrackThumbnail {
    if (nil != musicPlayer.nowPlayingItem) {
        UIImage *ablum = [musicPlayer.nowPlayingItem.artwork imageWithSize:CGSizeMake(320, 320)];
        if (nil != ablum) {
            return ablum;
        }
    }
    return [UIImage imageNamed:@"musicAlbum"];
}

- (MPMusicPlaybackState)currentPlayStatus {
    return musicPlayer.playbackState;
}

- (NSTimeInterval)currentPlaybackTime {
    return musicPlayer.currentPlaybackTime;
}

- (void)setPlaybackTime:(NSTimeInterval)startTime {
    [musicPlayer setCurrentPlaybackTime:startTime];
}

- (NSTimeInterval)currentPlaybackDuration {
    return musicPlayer.nowPlayingItem.playbackDuration;
}

@end
